<!-- 编辑,增加,复制用户弹窗页面 -->
<template>
  <el-dialog
    v-dialogDrag
    title="用户信息"
    :visible.sync="isDialogFormShow"
    width="50%"
    :before-close="closeDialog"
  >
    <el-form
      ref="userForm"
      :model="userForm"
      :rules="userRule"
      label-position="left"
      label-width="80px"
    >
      <el-row class="userFormItem">
        <el-col :span="10">
          <el-form-item prop="code" label="工号">
            <el-input id="txtUserCode" ref="code" v-model="userForm.code" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item prop="name" label="用户名">
            <el-input id="txtUserName txtUpdateUserName" ref="name" v-model="userForm.name" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="userFormItem">
        <el-col :span="10">
          <el-form-item id="chkSexMan" prop="sex" label="性别">
            <el-radio v-model="userForm.sex" :label="0">男</el-radio>
            <el-radio v-model="userForm.sex" :label="1">女</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item prop="password" label="密码">
            <el-input id="txtPassword" ref="password" v-model="userForm.password" type="password" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="userFormItem">
        <el-col :span="10">
          <el-form-item prop="departmentId" label="所属部门">
            <el-select ref="departmentId" v-model="userForm.departmentId">
              <el-option
                v-for="item in departmentData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                placeholder="请选择"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item prop="positionId" label="职位">
            <el-select ref="positionId" v-model="userForm.positionId">
              <el-option
                v-for="item in positionData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                placeholder="请选择"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="userFormItem">
        <el-col :span="10">
          <el-form-item prop="tel" label="电话">
            <el-input id="txtTel" ref="tel" v-model="userForm.tel" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item prop="email" label="邮箱">
            <el-input ref="email" v-model="userForm.email" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="userFormItem">
        <el-col :span="10">
          <el-form-item prop="roleList" label="拥有角色">
            <el-select ref="roleList" v-model="userForm.roleList" multiple>
              <el-option
                v-for="item in roleData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                placeholder="请选择"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item prop="other" label="其他联系">
            <el-input ref="other" v-model="userForm.other" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="userFormItem">
        <el-col :span="10">
          <el-form-item prop="birthday" label="生日">
            <el-date-picker
              v-model="userForm.birthday"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item prop="remark" label="备注">
            <el-input ref="remark" v-model="userForm.remark" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button id="btnOK" type="primary" @click="operateUser(operateType, 'userForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  add,
  modify,
  queryUserById
} from '@/api/right/user'
import { mapState } from 'vuex'

export default {
  name: 'DialogForm',
  props: {
    isDialogFormShow: {
      require: true,
      type: Boolean,
      default: false
    },
    operateType: {
      require: true,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 弹窗数据
      userForm: {
        code: '',
        name: '',
        sex: '',
        password: '',
        departmentId: '',
        positionId: '',
        tel: '',
        email: '',
        roleList: [],
        other: '',
        birthday: '',
        remark: '',
        modifier: ''
      },
      // 弹窗数据校验规则
      userRule: {
        code: [
          { required: true, message: '请输入工号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^(?!([a-zA-Z]+|\d+)$)[a-zA-Z\d]{6,20}$/,
            message: '密码由6-20位字母和数字组成',
            trigger: 'blur'
          }
        ],
        departmentId: [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ],
        positionId: [
          { required: true, message: '请选择职位', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
            message: '请输入正确的邮箱地址',
            trigger: 'blur'
          }
        ],
        roleList: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    /**
     * 获取角色，部门，职位信息
     */
    ...mapState(
      'user', [
        'roleData',
        'departmentData',
        'positionData'
      ]
    )
  },
  watch: {
    isDialogFormShow: {
      handler(newVal, oldVal) {
        if (!newVal && oldVal) {
          // 关闭弹窗时清楚校验错误提示信息
          this.$refs.userForm.clearValidate()
        }
      }
    }
  },
  mounted() {
    this.$nextTick(function() {
      /**
       * 编辑和复制时根据id获取用户信息
       */
      this.$on('updateUserFrom', async(row) => {
        this.getUserDataById(row.id)
      })
    })
  },
  methods: {
    /**
     * 关闭弹窗
     */
    closeDialog() {
      this.userForm = {
        code: '',
        name: '',
        sex: '',
        password: '',
        departmentId: '',
        positionId: '',
        tel: '',
        email: '',
        roleList: [],
        other: '',
        birthday: '',
        remark: '',
        modifier: ''
      }
      this.$emit('closeDialog')
    },
    /**
     * 编辑和复制时根据id获取用户信息,回填至弹窗数据
     * @param {*} id 用户Id
     */
    async getUserDataById(id) {
      try {
        let res = await queryUserById(id)
        if (res) {
          // COPY模式去除多余数据,EDIT模式接收全部数据
          if (this.operateType === 'COPY') {
            for (let key in res) {
              if (this.userForm[key] !== undefined && this.userForm[key] !== null) {
                this.userForm[key] = res[key]
              }
            }
            this.userForm.code = ''
            this.userForm.tel = ''
          } else {
            this.userForm = res
          }
          // 设置密码为空,用户重新设置密码
          this.userForm.password = ''
          // 修改roleList为接口的格式
          this.userForm.roleList = this.userForm.roleList.map((item) => item.id)
        } else {
          this.$message.error('该用户不存在')
          this.closeDialog()
        }
      } catch {
        this.$message.error('网络错误')
        this.closeDialog()
      }
    },
    /**
     * 操作用户
     * @param {*} type 操作类型 add edit copy
     * @param {*} formName ref，用于校验规则
     */
    operateUser(type, formName) {
      // 规则校验
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          try {
            this.userForm.modifier = this.$store.getters.name
            // 将roleList改成接口对应得格式
            let roles = []
            if (this.userForm.roleList) {
              this.userForm.roleList.map(item => {
                roles.push({ id: item })
              })
            }
            this.userForm.roleList = roles

            // 调用接口
            if (type === 'ADD' || type === 'COPY') {
              let res = await add(this.userForm)
              if (res) {
                this.$message.success('用户添加成功')
                this.$emit('operateUserSuccess')
                this.closeDialog()
              } else {
                this.$message('工号与手机号不得重复')
                this.closeDialog()
              }
            } else if (type === 'EDIT') {
              let res = await modify(this.userForm)
              if (res) {
                this.$message.success('用户修改成功')
                this.$emit('operateUserSuccess')
                this.closeDialog()
              } else {
                this.$message('编号不得重复')
              }
            }
          } catch {
            this.$message('网络错误')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.closeButton{
  width: 20px;
  height: 20px;
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 15px;
  cursor: pointer;
}
.closeButton:hover {
  color: #409EFF;
}
.userFormItem{
  margin: auto;
  display: flex;
  justify-content: space-between;
}
</style>
